"""
角色管理API
"""
from fastapi import APIRouter, HTTPException, status, Depends, Request
from typing import Optional
from models.m import Role, Resource, OperationLog, AdminUser
from schemas.admin_schemas import (
    RoleCreate, RoleUpdate, RoleResponse,
    ResponseModel, AssignResourcesRequest
)
from utils.auth_middleware import get_current_user
from tortoise.expressions import Q


role_router = APIRouter(prefix="/admin/roles", tags=["角色管理"])


@role_router.get("", response_model=ResponseModel, summary="获取角色列表")
async def get_roles(
    page: int = 1,
    page_size: int = 10,
    keyword: Optional[str] = None,
    status: Optional[int] = None,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取角色列表（支持分页、搜索）
    """
    query = Role.all()
    
    if keyword:
        query = query.filter(
            Q(name__icontains=keyword) | Q(code__icontains=keyword)
        )
    
    if status is not None:
        query = query.filter(status=status)
    
    # 统计总数
    total = await query.count()
    
    # 分页查询
    offset = (page - 1) * page_size
    roles = await query.offset(offset).limit(page_size)
    
    # 组装响应
    items = []
    for role in roles:
        items.append({
            "id": role.id,
            "name": role.name,
            "code": role.code,
            "description": role.description,
            "status": role.status,
            "create_time": role.create_time.isoformat(),
            "update_time": role.update_time.isoformat(),
        })
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "total": total,
            "page": page,
            "page_size": page_size,
            "items": items
        }
    }


@role_router.get("/all", response_model=ResponseModel, summary="获取所有角色（不分页）")
async def get_all_roles(current_user: AdminUser = Depends(get_current_user)):
    """
    获取所有启用的角色（用于下拉选择）
    """
    roles = await Role.filter(status=1).order_by('id')
    
    items = [{"id": role.id, "name": role.name, "code": role.code} for role in roles]
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": items
    }


@role_router.get("/{role_id}", response_model=ResponseModel, summary="获取角色详情")
async def get_role(
    role_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取指定角色的详细信息（包含权限资源）
    """
    role = await Role.get_or_none(id=role_id).prefetch_related('resources')
    
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    
    # 获取角色的资源ID列表
    resource_ids = [res.id for res in role.resources]
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": {
            "id": role.id,
            "name": role.name,
            "code": role.code,
            "description": role.description,
            "status": role.status,
            "resource_ids": resource_ids,
            "create_time": role.create_time.isoformat(),
            "update_time": role.update_time.isoformat(),
        }
    }


@role_router.post("", response_model=ResponseModel, summary="创建角色")
async def create_role(
    request: Request,
    role_data: RoleCreate,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    创建新角色
    """
    # 检查角色代码是否已存在
    existing = await Role.get_or_none(code=role_data.code)
    if existing:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色代码已存在")
    
    # 检查角色名称是否已存在
    existing = await Role.get_or_none(name=role_data.name)
    if existing:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色名称已存在")
    
    # 创建角色
    role = await Role.create(
        name=role_data.name,
        code=role_data.code,
        description=role_data.description,
        status=role_data.status
    )
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="create_role",
        module="角色管理",
        description=f"创建角色: {role.name}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=role_data.model_dump(),
        status=1
    )
    
    return {
        "code": 200,
        "message": "创建成功",
        "data": {"id": role.id}
    }


@role_router.put("/{role_id}", response_model=ResponseModel, summary="更新角色")
async def update_role(
    request: Request,
    role_id: int,
    role_data: RoleUpdate,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    更新角色信息
    """
    role = await Role.get_or_none(id=role_id)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    
    # 不能修改超级管理员角色
    if role.code == "super_admin":
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不能修改超级管理员角色")
    
    # 检查名称是否重复
    if role_data.name is not None and role_data.name != role.name:
        existing = await Role.get_or_none(name=role_data.name)
        if existing:
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色名称已存在")
        role.name = role_data.name
    
    # 更新字段
    if role_data.description is not None:
        role.description = role_data.description
    if role_data.status is not None:
        role.status = role_data.status
    
    await role.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="update_role",
        module="角色管理",
        description=f"更新角色: {role.name}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=role_data.model_dump(exclude_none=True),
        status=1
    )
    
    return {
        "code": 200,
        "message": "更新成功",
        "data": None
    }


@role_router.delete("/{role_id}", response_model=ResponseModel, summary="删除角色")
async def delete_role(
    request: Request,
    role_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    删除角色（软删除）
    """
    role = await Role.get_or_none(id=role_id)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    
    # 不能删除超级管理员和预设角色
    if role.code in ["super_admin", "admin", "staff", "customer_service"]:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="不能删除系统预设角色")
    
    # 检查是否有用户使用该角色
    user_count = await AdminUser.filter(role_id=role_id).count()
    if user_count > 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST, 
            detail=f"该角色下还有 {user_count} 个用户，无法删除"
        )
    
    # 软删除
    role.status = 0
    await role.save()
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="delete_role",
        module="角色管理",
        description=f"删除角色: {role.name}",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        status=1
    )
    
    return {
        "code": 200,
        "message": "删除成功",
        "data": None
    }


@role_router.post("/{role_id}/resources", response_model=ResponseModel, summary="分配资源权限")
async def assign_resources(
    request: Request,
    role_id: int,
    assign_data: AssignResourcesRequest,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    为角色分配资源权限
    """
    role = await Role.get_or_none(id=role_id)
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    
    # 验证所有资源是否存在
    resources = await Resource.filter(id__in=assign_data.resource_ids)
    if len(resources) != len(assign_data.resource_ids):
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="部分资源不存在")
    
    # 清除旧的关联，添加新的关联
    await role.resources.clear()
    await role.resources.add(*resources)
    
    # 记录操作日志
    await OperationLog.create(
        user_id=current_user.id,
        action="assign_resources",
        module="角色管理",
        description=f"为角色 {role.name} 分配权限",
        ip=request.client.host,
        user_agent=request.headers.get("user-agent"),
        request_data=assign_data.model_dump(),
        status=1
    )
    
    return {
        "code": 200,
        "message": "分配成功",
        "data": None
    }


@role_router.get("/{role_id}/resources", response_model=ResponseModel, summary="获取角色的资源权限")
async def get_role_resources(
    role_id: int,
    current_user: AdminUser = Depends(get_current_user)
):
    """
    获取角色拥有的所有资源权限
    """
    role = await Role.get_or_none(id=role_id).prefetch_related('resources')
    if not role:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="角色不存在")
    
    resources = []
    for res in role.resources:
        resources.append({
            "id": res.id,
            "name": res.name,
            "code": res.code,
            "type": res.type,
            "path": res.path,
            "icon": res.icon,
        })
    
    return {
        "code": 200,
        "message": "获取成功",
        "data": resources
    }

